export const setProperty = (prop: string, val: any, dom = document.documentElement) => {
    dom.style.setProperty(prop, val);
};

export const mix = (color1: string, color2: string, weight: number = 0.5): string => {
    let color = '#';
    for (let i = 0; i <= 2; i++) {
        const c1 = parseInt(color1.substring(1 + i * 2, 3 + i * 2), 16);
        const c2 = parseInt(color2.substring(1 + i * 2, 3 + i * 2), 16);
        const c = Math.round(c1 * weight + c2 * (1 - weight));
        color += c.toString(16).padStart(2, '0');
    }
    return color;
};

/**
 * 通用Excel导入函数
 * @param file Excel文件
 * @returns Promise解析后的数据
 */
export const importExcel = (file: File): Promise<any[]> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e: any) => {
            try {
                const data = e.target.result;
                import('xlsx').then(XLSX => {
                    const workbook = XLSX.read(data, { type: 'binary' });
                    const sheetName = workbook.SheetNames[0];
                    const result = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
                    resolve(result);
                }).catch(error => {
                    reject(new Error('加载XLSX库失败: ' + error.message));
                });
            } catch (error: any) {
                reject(new Error('解析Excel文件失败: ' + error.message));
            }
        };
        reader.onerror = (error) => {
            reject(new Error('读取文件失败: ' + error.message));
        };
        reader.readAsBinaryString(file);
    });
};

/**
 * 通用Excel导入处理函数，用于处理Element Plus Upload组件
 * @param options Element Plus Upload组件的options参数
 * @param handler 数据处理函数
 * @returns Promise
 */
export const handleExcelImport = async (options: any, handler: (data: any[]) => Promise<any>): Promise<void> => {
    const { file, onSuccess, onError, onProgress } = options;
    
    try {
        // 更新进度
        onProgress({ status: 'uploading' }, file);
        
        // 解析Excel文件
        const data = await importExcel(file);
        
        // 处理解析后的数据
        await handler(data);
        
        // 成功回调
        onSuccess('导入成功', file);
    } catch (error: any) {
        // 错误回调
        onError(error);
        throw error;
    }
};